<script>
import {confirm, toast} from "../js/vant_tool.js";
import {generateTOTP_fix} from "../js/totp.js";

export default {
  data(){
    return {
      keys: [],
      th: null,
      formData: {
        name: '',
        secret: '',
        prefix: '',
        suffix: '',
      },
      tab: 0,
    }
  },
  methods: {
    loadKeys(){
      const keysStr = localStorage.getItem('totpKeys');
      let keys = [];
      try {
        keys = keysStr ? JSON.parse(keysStr) : [];
      } catch (e) {
      }
      return keys;
    },
    saveKeys(keys){
      localStorage.setItem('totpKeys', JSON.stringify(keys));
    },
    copy(key){
      navigator.clipboard.writeText(key.tokenCode).then(() => {
        toast(`"${key.name}"的密码已复制到剪贴板`);
      });
    },
    async del(i){
      confirm('是否确定删除');
      let keys = this.loadKeys();
      keys.splice(i, 1);
      this.saveKeys(keys);
      this.init();
    },
    getRemainingTime() {
      const now = new Date();
      const seconds = now.getSeconds();
      return 30 - (seconds % 30);
    },
    init(){
      let keys = this.loadKeys();
      console.log(keys);
      let remainingTime = this.getRemainingTime()
      this.keys = keys.filter(key=>{
        if (!key.secret || !key.name) return false;
        key.prefix = key.prefix || '';
        key.suffix = key.suffix || '';
        key.remainingTime = remainingTime;
        generateTOTP_fix(key.secret, key.prefix, key.suffix).then(tokenCode => {
          key.tokenCode = tokenCode;
        }).catch(e=>{
          key.tokenCode = `TOTP密钥错误：${key.secret}`
        });
        return key;
      })
      console.log(this.keys)
    },
    add(){
      if (!this.formData.name || !this.formData.secret) {
        toast('请填写密钥名称和TOTP密钥');
        return;
      }
      const keys = this.loadKeys();
      keys.push(this.formData);
      this.saveKeys(keys);
      this.formData.name = '';
      this.formData.secret = '';
      this.formData.prefix = '';
      this.formData.suffix = '';
      toast('添加成功');
      this.init();
    },
    select_file(){
      const files = window.utools.showOpenDialog({
        title: '选择文件',
        properties: ['openFile']
      })
      if (!files) return
      const _filePath = files[0];
      let content = '';
      try {
        content = window.services.readFile(_filePath)
      } catch (err) {
      }
      toast(content);
    }
  },
  mounted() {
    this.init();
    this.th = setInterval(()=>{
      let remainingTime = this.getRemainingTime();
      this.keys.forEach(key=>{
        if (remainingTime > key.remainingTime){
          generateTOTP_fix(key.secret, key.prefix, key.suffix).then(tokenCode => {
            key.tokenCode = tokenCode;
          }).catch(e=>{
            key.tokenCode = `TOTP密钥错误：${key.secret}`
          });
        }
        key.remainingTime = remainingTime;
      })
    }, 1000)
  },
  unmounted() {
    if (this.th) clearInterval(this.th);
  }
}
</script>

<template>
  <div class="container">
    <header>
      <h1>TOTP动态密码生成器</h1>
      <p class="description">基于时间的一次性密码算法，支持前后缀配置</p>
    </header>

    <div class="main-content">
      <div class="tokens-section">
        <h2>已缓存的密钥</h2>
        <div id="token-list" class="token-list">
          <!-- 动态生成的令牌卡片将在这里显示 -->
          <div v-if="!keys.length" class="empty-state">
            <p>暂无密钥配置，请先添加密钥</p>
          </div>
          <div v-for="(key, i) in keys" class="token-card" @click="copy(key)">
            <div class="flex">
              <div class="token-name max text-ellipsis">{{key.name}}</div>
              <button class="btn btn-danger delete-btn" @click.stop="del(i)">删除</button>
            </div>
            <div class="token-code text-ellipsis">{{key.tokenCode}}</div>
            <div class="token-time">{{key.remainingTime}}秒后更新</div>
            <div class="progress-bar">
              <div class="progress" :style="{width: `${(key.remainingTime / 30) * 100}%`}"></div>
            </div>
          </div>
        </div>
      </div>

      <div class="tabs flex">
        <div class="tab max" :class="{on:tab===0}" @click="tab=0">添加新密钥</div>
        <div class="tab max" :class="{on:tab===1}" @click="tab=1">批量添加</div>
      </div>

      <div v-if="tab===0" class="form-section">
        <div class="form-group">
          <label for="key-name">密钥名称</label>
          <input type="text" v-model="formData.name" placeholder="便于识别的名称">
        </div>
        <div class="form-group">
          <label for="totp-secret">TOTP密钥</label>
          <input type="text" v-model="formData.secret" placeholder="输入TOTP密钥（Base32编码）">
        </div>
        <div class="form-group">
          <label for="prefix">前缀（可选）</label>
          <input type="text" v-model="formData.prefix" placeholder="">
        </div>
        <div class="form-group">
          <label for="suffix">后缀（可选）</label>
          <input type="text" v-model="formData.suffix" placeholder="">
        </div>
        <button id="add-key" class="btn btn-primary" @click="add">添加密钥</button>
      </div>

      <div v-if="tab===1" class="add-batch">
        <input type="file" accept="text/plain" id="input_file" style="display: none;" @change="select_file_after">
        <button class="btn btn-primary" @click="select_file">选择文件(txt)</button>
        <p>选择一个记录了多个密钥的文件，格式如下：</p>
        <pre class="code">
密钥名称1
密钥...
前缀（可选）
后缀（可选）

密钥名称2
密钥...
        </pre>
      </div>

    </div>

  </div>

</template>

<style scoped>
.container {
  max-width: 800px;
  margin: 0 auto;
  background: var(--color-bg);
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.code{padding: 10px;background: var(--color-bg-re); color: var(--color-bg);border-radius: 10px;position: relative;}

.tabs{width: 100%;overflow: auto hidden;}
.tabs .tab{text-align: center;padding: 10px;position: relative;}
.tabs .tab.on::after{content: '';display: block;width: 2em;height: 6px;border-radius: 3px;background-color: var(--color-primary);position: absolute;bottom: 0;left: calc(50% - 1em)}

header {
  background: var(--color-primary);
  color: var(--color-primary-re);
  padding: 20px;
  text-align: center;
}

h1 {
  margin-bottom: 10px;
}

.description {
  font-size: 0.9rem;
  opacity: 0.9;
}

.main-content {
  padding: 20px;
}

.form-section {
  background: var(--color-bg);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 600;
}

input[type="text"] {
  width: 100%;
  padding: 10px;
  border: 1px solid var(--color-bg-re-r);
  background: var(--color-bg);
  color: var(--color-bg-re);
  border-radius: 4px;
  font-size: 16px;
}

.btn {
  display: inline-flex;
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s;
  width: auto;
}

.btn-primary {
  background: var(--color-primary);
  color: var(--color-primary-re);
}

.btn-primary:hover {
  background: #3a5bd9;
}

.btn-danger {
  background: var(--color-error);
  color: var(--color-error-re);
}

.btn-danger:hover {
  background: #c82333;
}

.tokens-section {
  margin-top: 20px;
}

.token-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
}

.token-card {
  background: var(--color-bg);
  border: 1px solid var(--color-bg-re-r);
  border-radius: 8px;
  padding: 15px;
  transition: all 0.3s;
  cursor: pointer;
  position: relative;
}

.token-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.token-name {
  font-size: 1.4em;
  font-weight: bold;
  margin-bottom: 10px;
  color: var(--color-primary);
}

.token-code {
  font-size: 1.5rem;
  font-weight: bold;
  letter-spacing: 2px;
  margin: 10px 0;
  text-align: center;
  background: var(--color-bg);
  padding: 10px;
  border-radius: 4px;
  width: 100%;
  overflow: hidden;
}

.token-time {
  font-size: 0.8rem;
  color: var(--color-bg-re-1);
  text-align: center;
}

.progress-bar {
  height: 5px;
  background: var(--color-bg-1);
  border-radius: 5px;
  margin-top: 10px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background: var(--color-primary);
  width: 100%;
  transition: width 1s linear;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: var(--color-bg-re-r);
}

@media (max-width: 600px) {
  .token-list {
    grid-template-columns: 1fr;
  }
}
</style>